package com.mission.schedule.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.mission.schedule.cutimage.Log;

import java.io.File;

/**
 * Created by liwei on 2017/5/12.
 */

public class DownImageService extends Service {


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if (intent != null){
            downimage(intent.getStringExtra("url"),intent.getStringExtra("name"));
        }
    }

    private void downimage(String url, String savename){
        String dicr = Environment.getExternalStorageDirectory()+"/DCIM/";
        File outfile = new File(dicr,"TimeApp");
        // 如果文件不存在，则创建一个新文件
        if (!outfile.isDirectory()) {
            try {
                outfile.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Bitmap bitmap = BitmapFactory.decodeFile(outfile + "/" + savename);

        if (bitmap == null) {
            HttpUtils httpUtils = new HttpUtils(10000);
            httpUtils.download(url, outfile + "/" + savename, new RequestCallBack<File>() {
                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    Log.e("TAG"," note image down ok");
                }

                @Override
                public void onFailure(HttpException e, String s) {

                }
            });
        }

    }

}
